import Group from './group'
import User from './user'
import { isString } from '../utils/index'

class UserGroup {
  constructor() {
    // 组
    this.state = [
      // {
      //   id: '', //
      //   uid: '',
      //   gid: '' // 分组id
      // }
    ]
    this.instance = null
  }

  static getInstance() {
    if (!this.instance) {
      this.instance = new UserGroup()
    }
    return this.instance
  }

  /**
   * @param {*} gid
   */
  checkGroup(gid) {
    let valid = Group.state.some(v => {
      return v.gid === gid
    })
    return valid
  }
  /**
   * @param {*} uid
   */
  checkUser(uid) {
    let valid = User.state.some(v => {
      return v.uid === uid
    })
    return valid
  }
  /**
   * 设置
   * @param {*} item
   */
  setState(item) {
    if (!item) {
      return false
    }
    if (isString(item.gid) && isString(item.uid)) {
      let checkGroup = this.checkGroup(item.gid)
      if (!checkGroup) {
        return false
      }
      let checkUser = this.checkUser(item.uid)
      if (!checkUser) {
        return false
      }
      item['id'] = this.state.length
      item['code'] = `${item.gid}_${item.uid}`
      let valid = this.state.some(v => {
        return v.code === item.code
      })
      if (!valid) {
        this.state.push(item)
      }
    }
    return false
  }
  /**
   * 获取
   * @param {object} item
   */
  getState(item = { uid: '', gid: '' }) {
    if (item && (item.gid || item.uid)) {
      if (isString(item.gid) && isString(item.uid)) {
        return this.state.filter(v => {
          return v.code === `${item.gid}_${item.uid}`
        })
      } else if (isString(item.gid)) {
        return this.state.filter(v => {
          return v.gid === item.gid
        })
      } else if (isString(item.uid)) {
        return this.state.filter(v => {
          return v.uid === item.uid
        })
      }
    }
    return []
  }
}

let _userGroup = UserGroup.getInstance()
export default _userGroup
